//
// Created by 沈昊 on 2022/2/22.
//
#include "VaryFrameWriter.h"
#include <Util/logger.h>
VaryFrameWriter::VaryFrameWriter(size_t width, size_t height, const AVCodecID& id):width(width), height(height), id(id){

}
bool VaryFrameWriter::inputFrame(const mediakit::Frame::Ptr &frame){
    //由此收到数据
    if(!decoder && !encoder){
        initiallze(frame->getCodecId());
    }
    if(decoder){
        decoder->inputFrame(frame->data(), frame->size());
    }
    return true;
}

void VaryFrameWriter::initiallze(const mediakit::CodecId& id){
    switch (id) {
    case mediakit::CodecH264:{
        InfoL << "已经初始化H264解码器";
        decoder = std::make_shared<FFmpegDecoder>(AVCodecID::AV_CODEC_ID_H264);
        encoder = std::make_shared<FFmpegEncoder<CoderTransfer<Video>>>(this->id);

        //auto func = std::bind(&VaryFrameWriter::OnVaryFrame, this, std::placeholders::_1, std::placeholders::_2);
        decoder->setOnDecoder([&](const CoderContext& context, const typename Rawpgm::Ptr& ptr){
            std::call_once(this->flag, [&](){
                encoder->Scale(width, height);
                encoder->setTimeBase(context.TimeBase());
                encoder->PixFmt(context.PixFormat());
                encoder->CreateTransfer(context.Width(), context.Height(), context.PixFormat(),
                                        context.TimeBase(), context.SampleAspectRatio());
                encoder->setOnFrame(this->func);
            });
            encoder->readFrame(ptr);
        });
        break;
    }
    default:
        InfoL << "忽略: " << getCodecName(id);
        break;
    }
}

void VaryFrameWriter::setOnVaryFrame(std::function<void(const CoderContext&, FFmpeg::Frame::Ptr)>&&  func){
   this->func = std::move(func);
}